
import { ApplicationCategory, Application } from '../types';

import { API_BASE_URL, getToken, readTextFromFile, request } from '../../utils';
import { G01_FORM_SCHEMA_CLASS_IDENTIFIER, G01_MODEL_PROVIDER_CLASS_IDENTIFIER } from './constants';
import { dsFind, dsFindOne, dsInsert, dsUpdateById, dsUpdateByKeys, ComparsionOperator } from '../local';
import { PROJECT_APPLICATION_CLASS_IDENTIFIER } from '../constants';
import { writeTextFile } from '@tauri-apps/plugin-fs';


export const localAppFetchAppDetail = async (app_identifier: string): Promise<{
    application: any,
    content: any
} | null> => {

    //获取本地文件地址
    try {
        let appRes = await dsFindOne(0, PROJECT_APPLICATION_CLASS_IDENTIFIER, {
            attributes: [{
                name: "identifier",
                operator: ComparsionOperator.Equal,
                value: app_identifier
            }]
        });

        console.log(appRes);
        let filePath = appRes.path;
        //读取文件
        let content = await readTextFromFile(filePath, {});
        console.log(typeof content);
        if (content) {
            if (typeof content === 'string') {
                return {
                    application: appRes,
                    content: JSON.parse(content)
                };
            } else {
                //arraybuffer
                const decoder = new TextDecoder("UTF-8");
                return {
                    application: appRes,
                    content: JSON.parse(decoder.decode(content))
                };
            }
        }
    } catch (err) {
        console.log("########30");
        console.log(err);
    }
    return null;
}


export const localAppUpdateAppConfig = async (app_identifier: string, config: any): Promise<void> => {
    //获取本地文件地址
    try {
        let appRes = await dsFindOne(0, PROJECT_APPLICATION_CLASS_IDENTIFIER, {
            attributes: [{
                name: "identifier",
                operator: ComparsionOperator.Equal,
                value: app_identifier
            }]
        });

        console.log(appRes);
        let filePath = appRes.path;
        //写文件
        await writeTextFile(filePath, JSON.stringify(config));
    } catch (err) {
        console.log("########30");
        console.log(err);
    }
    return null;
}